package StudyCode.Reflect.ObjectAnalyzer;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

/**
 * @author lixiaoyao
 * @date 2018/10/23 0023、上午 8:27
 * @description
 */
public class ObjectAnalyzer {

	private ArrayList<Object> visited = new ArrayList<>();

	public String toString(Object obj) {
		if (obj == null) {
			return "null";
		}
		if (this.visited.contains(obj)) {
			return "...";
		}
		this.visited.add(obj);
		Class cl = obj.getClass();
		if (cl == String.class) {
			return (String) obj;
		}
		if (cl.isArray()) {
			String r = cl.getComponentType() + "[]{";
			for (int i = 0; i < Array.getLength(obj); i++) {
				if (i > 0) {
					r += ",";
				}
				Object val = Array.get(obj, i);
				if (cl.getComponentType().isPrimitive()) {
					r += val;
				} else {
					r += toString(val);
				}
			}
			return r + "}";
		}

		String r = cl.getName();
		// inspect thd fields of this class and all superclasses
		do {
			r += "[";
			Field[] fields = cl.getDeclaredFields();
			AccessibleObject.setAccessible(fields, true);
			// get the names and values of all fields
			for (Field field : fields) {
				if (!Modifier.isStatic(field.getModifiers())) {
					if (!r.endsWith("[")) {
						r += ",";
					}
					r += field.getName() + "=";
					try {
						Class t = field.getType();
						Object val = field.get(obj);
						if (t.isPrimitive()) {
							r += val;
						} else {
							r += toString(val);
						}
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
			r += "]";
			cl = cl.getSuperclass();
		} while (cl != null);
		return r;
	}

}
